package com.bidevalution.support.util;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.apache.pdfbox.io.RandomAccessBufferedFileInputStream;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.*;

/**
 * 文件格式转换工具类
 * Created by glodon on 2019-08-13.
 */
public class FileTypeConvertUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileTypeConvertUtil.class);

    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     * @param htmlStr
     * @param pdfFile
     * @throws Exception
     */
    public static void htmlText2pdf(String htmlStr, String pdfFile) throws Exception {
        OutputStream os = null;
        try {
            os = new FileOutputStream(pdfFile);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(htmlStr);

            //解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            if ("linux".equals(getCurrentOperatingSystem())) {
                fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            } else {
                fontResolver.addFont("c:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
    }


    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     * @param htmlFile
     * @param pdfFile
     * @throws Exception
     */
    public static void htmlFile2pdf(String htmlFile, String pdfFile) throws Exception{
        // step 1
        OutputStream os = null;
        try {
            String url = new File(htmlFile).toURI().toURL().toString();
            System.out.println(url);
            // step 2
            os = new FileOutputStream(pdfFile);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);

            // step 3 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            if ("linux".equals(getCurrentOperatingSystem())) {
                fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            } else {
                fontResolver.addFont("c:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }

            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
        System.out.println("create pdf done!!");
    }

    public static String getCurrentOperatingSystem(){
        String os = System.getProperty("os.name").toLowerCase();
        System.out.println("---------当前操作系统是-----------" + os);
        return os;
    }

    /**
     * @param
     * @return
     * @throws Exception
     */

    public static void readPdf(BufferedWriter writer, String fileName) throws IOException {

        String content = null;
        PDDocument pdfdocument = null;
        RandomAccessBufferedFileInputStream raFile = null;
        try {
            raFile = new RandomAccessBufferedFileInputStream(fileName);
            logger.info("pdf文件长度>>>>>>>>>>>>>>>>>:"+raFile.length());
            PDFParser parser = new PDFParser(raFile);
            parser.parse();
            pdfdocument = parser.getPDDocument();
            PDFTextStripper stripper = new PDFTextStripper();
            content = stripper.getText(pdfdocument);
            writer.write(content);
            
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        } finally {
        	//add by daizhifeng 关闭文件流；所有关闭操作放到finally
        	if(raFile != null) {
        		raFile.close();
        	}
        	if(pdfdocument != null) {
        		pdfdocument.close();
        	}
            writer.close();
        }
    }

    public static void main(String[] args) {
       /* String htmlFile = "d:/table.html";
        String pdfFile = "d:/testoone2.pdf";
        try {
            FileTypeConvertUtil.htmlFile2pdf(htmlFile, pdfFile);
        } catch (Exception e) {
        }*/
        String str ="<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                "<head>\n" +
                "  <meta charset=\"UTF-8\"/>\n" +
                "  <title>承诺书</title>\n" +
                "  <meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width\"/>\n" +
                "  <link rel=\"stylesheet\" href=\"https://static.loyalvalleycapital.com/web/css/frame.css\"/>\n" +
                "  <style>\n" +
                "</style>\n" +
                "</head>\n" +
                "<body class=\"bg-white pb-3\"  style = \"font-family: SimSun;\">\n" +
                "<div style=\"max-width:600px;margin:0 auto;padding:10px;\">\n" +
                "  <div class=\"f18 text-center mv-2 bold\">专家承诺书</div>\n" +
                "  <div class=\"f12 mb\">\n" +
                "\t\t<p>  本人作为评委，在参加XXXX组织的xxxx项目的评审工作大幅度\n" +
                "\t\t中，将遵循《中华人民共和国招投标法》，认真执行发发发大润发\n" +
                "\t\t政府采购制度、严格履行评委职责，本着公正、公平、公开原则\n" +
                "\t\t单连同缴款通知书、现金或转账支票一并交银行柜台办理交款业务。\n" +
                "\t\t银行收妥后，即开具浙江省财政厅监制的浙江省非税收人统一票据。\n" +
                "\t\t你单位（个人）缴款后，请凭收款银行开具的收费票据（执收单位\n" +
                "\t\t统计联）到我单位继续办理有关业务。\n" +
                "\t\t</p>\n" +
                "\t</div>\n" +
                "\t<div align=\"left\"><p>评审专家签名：</p></div>\n" +
                "\t<div align=\"left\"><p>年  月  日</p></div>\t\t\t\t\t\t\t\n" +
                "</div>\n" +
                "\n" +
                "</body>\n" +
                "</html>";
        String pdfFile = "d:/testoone2.pdf";
        try {
            FileTypeConvertUtil.htmlText2pdf(str, pdfFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }
}
